<template>
  <div class="theme-selector">
    <!-- 主题切换按钮 -->
    <div class="relative">
      <button
        @click="showThemeMenu = !showThemeMenu"
        @click.stop
        class="theme-toggle-btn flex items-center space-x-2 px-3 py-2 rounded-lg transition-all duration-300"
        :class="themeButtonClass"
        type="button"
        :title="ts('切换主题')"
      >
        <component :is="currentThemeIcon" class="w-5 h-5" />
        <span class="text-sm hidden sm:inline">{{ currentThemeName }}</span>
        <ChevronDown 
          class="w-4 h-4 transition-transform duration-300" 
          :class="{ 'rotate-180': showThemeMenu }" 
        />
      </button>
      
      <!-- 主题选择菜单 -->
      <div 
        v-if="showThemeMenu"
        class="theme-menu absolute right-0 top-full mt-2 rounded-lg shadow-2xl min-w-[200px] overflow-hidden z-50"
        :class="menuClass"
        @click.stop
      >
        <!-- 主题选项 -->
        <div
          v-for="theme in availableThemes"
          :key="theme.id"
          @click="selectTheme(theme.id)"
          class="theme-option flex items-center space-x-3 px-4 py-3 cursor-pointer transition-colors"
          :class="getThemeOptionClass(theme.id)"
        >
          <component :is="getThemeIcon(theme.id)" class="w-5 h-5" />
          <div class="flex-1">
            <span class="font-medium">{{ theme.name }}</span>
            <div class="flex items-center space-x-1 mt-1">
              <div 
                v-for="color in getThemePreviewColors(theme.id)"
                :key="color"
                class="w-3 h-3 rounded-full border border-white/20"
                :style="{ backgroundColor: color }"
              ></div>
            </div>
          </div>
          <Check v-if="currentTheme === theme.id" class="w-4 h-4 text-green-400" />
        </div>
        
        <!-- 分割线 -->
        <div class="divider" :class="dividerClass"></div>
        
        <!-- 高级选项 -->
        <div class="px-4 py-3">
          <label class="flex items-center space-x-2 cursor-pointer">
            <input
              type="checkbox"
              v-model="followSystemTheme"
              @change="toggleSystemTheme"
              class="rounded"
              :class="checkboxClass"
            >
            <span class="text-sm" :class="textSecondaryClass">
              {{ ts('跟随系统主题') }}
            </span>
          </label>
        </div>
        
        <!-- 主题预览 -->
        <div class="theme-preview px-4 py-3" :class="previewBgClass">
          <div class="text-xs mb-2" :class="textSecondaryClass">{{ ts('预览效果') }}</div>
          <div class="preview-card p-3 rounded-lg" :class="previewCardClass">
            <div class="flex items-center space-x-2 mb-2">
              <div class="w-3 h-3 rounded-full" :style="{ backgroundColor: themeState.theme.colors.accent }"></div>
              <span class="text-sm font-medium" :class="textPrimaryClass">{{ ts('政策管理中心') }}</span>
            </div>
            <div class="text-xs" :class="textSecondaryClass">
              {{ ts('智能政策分析与决策支持') }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ChevronDown, Check, Sun, Moon, Monitor, Palette } from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import themeService, { themeState, THEME_TYPES } from '../services/themeService.js'

export default {
  name: 'ThemeSelector',
  components: {
    ChevronDown,
    Check,
    Sun,
    Moon,
    Monitor,
    Palette
  },
  
  emits: ['theme-changed'],
  
  setup(props, { emit }) {
    const { ts } = useTranslation()
    
    // 状态
    const showThemeMenu = ref(false)
    const followSystemTheme = ref(false)
    
    // 计算属性
    const currentTheme = computed(() => themeState.currentTheme)
    const currentThemeName = computed(() => themeState.theme.name)
    const availableThemes = computed(() => themeService.getAvailableThemes())
    
    const currentThemeIcon = computed(() => {
      return themeState.isDark ? Moon : Sun
    })
    
    // 样式类
    const themeButtonClass = computed(() => {
      if (themeState.isLight) {
        return 'bg-white/10 hover:bg-white/20 text-gray-700 border border-gray-300'
      } else {
        return 'bg-white/10 hover:bg-white/20 text-white border border-white/20'
      }
    })
    
    const menuClass = computed(() => {
      if (themeState.isLight) {
        return 'bg-white border border-gray-200'
      } else {
        return 'bg-gray-900 border border-gray-600'
      }
    })
    
    const textPrimaryClass = computed(() => {
      return themeState.isLight ? 'text-gray-900' : 'text-white'
    })
    
    const textSecondaryClass = computed(() => {
      return themeState.isLight ? 'text-gray-600' : 'text-white/70'
    })
    
    const dividerClass = computed(() => {
      return themeState.isLight ? 'bg-gray-200' : 'bg-white/10'
    })
    
    const checkboxClass = computed(() => {
      return themeState.isLight ? 'text-blue-600' : 'text-electric-500'
    })
    
    const previewBgClass = computed(() => {
      return themeState.isLight ? 'bg-gray-50' : 'bg-white/5'
    })
    
    const previewCardClass = computed(() => {
      if (themeState.isLight) {
        return 'bg-white border border-gray-200'
      } else {
        return 'bg-white/10 border border-white/20'
      }
    })
    
    // 方法
    const selectTheme = (themeId) => {
      if (themeService.switchTheme(themeId)) {
        showThemeMenu.value = false
        followSystemTheme.value = false
        
        emit('theme-changed', {
          theme: themeId,
          themeConfig: themeService.getCurrentThemeConfig()
        })
        
        console.log(`用户切换主题到: ${themeId}`)
      }
    }
    
    const toggleSystemTheme = () => {
      if (followSystemTheme.value) {
        themeService.followSystemTheme()
        showThemeMenu.value = false
      }
    }
    
    const getThemeIcon = (themeId) => {
      const iconMap = {
        [THEME_TYPES.DARK]: Moon,
        [THEME_TYPES.LIGHT]: Sun
      }
      return iconMap[themeId] || Palette
    }
    
    const getThemeOptionClass = (themeId) => {
      const isSelected = currentTheme.value === themeId
      
      if (themeState.isLight) {
        return isSelected 
          ? 'bg-blue-50 text-blue-700' 
          : 'text-gray-700 hover:bg-gray-100'
      } else {
        return isSelected 
          ? 'bg-blue-500/20 text-blue-400' 
          : 'text-white hover:bg-white/10'
      }
    }
    
    const getThemePreviewColors = (themeId) => {
      // 根据主题ID返回预览颜色
      if (themeId === THEME_TYPES.LIGHT) {
        return ['#0073e6', '#f8fafc', '#1e293b']
      } else {
        return ['#00f5ff', '#1a253d', '#ffffff']
      }
    }
    
    // 全局点击处理
    const handleGlobalClick = (event) => {
      const themeSelector = event.target.closest('.theme-selector')
      if (!themeSelector && showThemeMenu.value) {
        showThemeMenu.value = false
      }
    }
    
    // 键盘事件处理
    const handleKeydown = (event) => {
      if (event.key === 'Escape' && showThemeMenu.value) {
        showThemeMenu.value = false
      }
    }
    
    // 主题变化监听
    const handleThemeChange = (event) => {
      emit('theme-changed', event.detail)
    }
    
    // 生命周期
    onMounted(() => {
      document.addEventListener('click', handleGlobalClick)
      document.addEventListener('keydown', handleKeydown)
      window.addEventListener('themeChange', handleThemeChange)
      
      console.log('🎨 主题选择器已初始化')
    })
    
    onUnmounted(() => {
      document.removeEventListener('click', handleGlobalClick)
      document.removeEventListener('keydown', handleKeydown)
      window.removeEventListener('themeChange', handleThemeChange)
    })
    
    return {
      // 状态
      showThemeMenu,
      followSystemTheme,
      themeState,
      
      // 计算属性
      currentTheme,
      currentThemeName,
      currentThemeIcon,
      availableThemes,
      
      // 样式类
      themeButtonClass,
      menuClass,
      textPrimaryClass,
      textSecondaryClass,
      dividerClass,
      checkboxClass,
      previewBgClass,
      previewCardClass,
      
      // 方法
      selectTheme,
      toggleSystemTheme,
      getThemeIcon,
      getThemeOptionClass,
      getThemePreviewColors,
      
      // 翻译
      ts
    }
  }
}
</script>

<style scoped>
.theme-selector {
  @apply relative;
}

.theme-toggle-btn {
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.theme-toggle-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.theme-menu {
  backdrop-filter: blur(20px);
  animation: slideDown 0.2s ease-out;
}

.theme-option {
  transition: all 0.2s ease;
}

.theme-option:hover {
  transform: translateX(2px);
}

.divider {
  height: 1px;
  margin: 0.5rem 0;
}

.preview-card {
  transition: all 0.2s ease;
}

.preview-card:hover {
  transform: scale(1.02);
}

/* 动画 */
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 深色主题下的特殊效果 */
.theme-dark .theme-toggle-btn {
  box-shadow: 0 0 10px rgba(0, 245, 255, 0.2);
}

.theme-dark .theme-toggle-btn:hover {
  box-shadow: 0 0 20px rgba(0, 245, 255, 0.4);
}

/* 浅色主题下的特殊效果 */
.theme-light .theme-toggle-btn {
  box-shadow: 0 2px 8px rgba(0, 115, 230, 0.15);
}

.theme-light .theme-toggle-btn:hover {
  box-shadow: 0 4px 16px rgba(0, 115, 230, 0.25);
}

/* 确保z-index正确 */
.theme-menu {
  z-index: 9999;
}
</style> 